package com.datatraffic.salesup;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.datatraffic.salesup.anim.ActivityTransitionAnimation;
import com.datatraffic.services.ManagerExecutor;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.preference.PreferenceManager;

public class MainActivity extends Activity implements ConsumidorServicios {
	
	private TextView txtLogin = null;
	private TextView txtPassword = null;
	private SharedPreferences prefs;
	private ProgressDialog pd;
	
	private AlertDialog.Builder builderNoti;
	private AlertDialog builderNotiDos;
	
	private String celularDos="";
	private String nombreDos="";
	private String fechaDos="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        
        txtLogin = (TextView) findViewById(R.id.email);
		txtPassword = (TextView) findViewById(R.id.password);
		
		//txtLogin.setText("papi");
		//txtPassword.setText("qwerty");
		
		prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return super.onOptionsItemSelected(item);
    }
    
    public void handleLogin(View view) {
    	if(ValidarCampos())
    	{
    		JSONObject encuesta = new JSONObject();
    		try {
    			encuesta.put("function", "login");
    			encuesta.put("mobile_key", "356612021160629");
    			encuesta.put("resource", "356612021160629");
    			encuesta.put("ip", "127.0.0.01");
    			encuesta.put("user", txtLogin.getText().toString());
    			encuesta.put("password", md5Java(txtPassword.getText().toString()));

    			pd = new ProgressDialog(MainActivity.this);
    			pd.setCancelable(false);
    			pd.setMessage("Iniciando sesión");
    			pd.show();
    			ManagerExecutor executor = new ManagerExecutor(MainActivity.this, MainActivity.this.getBaseContext());
    			executor.execute(encuesta);

    		} catch (JSONException e) {
    			e.printStackTrace();
    		}    	
    	}
    }


    @Override
    public void procesarRespuesta(JSONObject json) {
    	
    	try
    	{
    		if(json!=null)
    		{
    			if(json.optString("error").equalsIgnoreCase("false"))
    			{
    				JSONArray data;
    				try {
    					data = json.getJSONArray("data");

    					if(data.length()>0)
    					{
    						int id = (int) data.optJSONObject(0).optLong("id");

    						if(id > 0)
    						{
    							Editor editor = prefs.edit();
    							editor.putString("idUsuario", String.valueOf(id));

    							editor.commit(); 
    							if (pd != null && pd.isShowing()) {
    								pd.dismiss();
    							}
    							Toast.makeText(this, "Ingreso exitoso!!!!", Toast.LENGTH_LONG).show();
    							Intent i = new Intent(MainActivity.this, MenuActivity.class);
    							startActivity(i); 
    							if (android.os.Build.VERSION.SDK_INT  > 4) {
    								ActivityTransitionAnimation.slide(MainActivity.this, ActivityTransitionAnimation.LEFT);
    							}

    						}
    					}				
    				} catch (JSONException e) {
    					e.printStackTrace();
    					if (pd != null && pd.isShowing()) {
    						pd.dismiss();
    					}
    					Toast.makeText(this, "Error en la comunicacion por favor intente de nuevo.!!!!", Toast.LENGTH_LONG).show();
    				}


    			}
    			else
    			{
    				if (pd != null && pd.isShowing()) {
    					pd.dismiss();
    				}
    				Toast.makeText(this, "Error en la comunicacion por favor intente de nuevo. Motivo del fallo: "+json.optString("msg"), Toast.LENGTH_LONG).show();
    			}
    		}
    	}
    	catch(Exception ex)
    	{

    	}
    }
    
    @Override
    protected void onResume() {
        super.onResume(); 
        
        prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        if(prefs.getString("notificacion", "").equalsIgnoreCase("ok"))
        {
        	Editor editor = prefs.edit();
    		editor.putString("notificacion","");
    		editor.commit();

			celularDos=prefs.getString("celular","");
    		fechaDos=prefs.getString("fecha","");
    		nombreDos=prefs.getString("nombre","");
    		Log.e("NOMBRE A COLOCAR", nombreDos);
        	runOnUiThread(new Runnable() {
        		public void run() {

        			LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        			View layout = inflater.inflate(R.layout.push,(ViewGroup) findViewById(R.id.layout));

        			TextView titulo=(TextView) layout.findViewById(R.id.title);
        			TextView text=(TextView) layout.findViewById(R.id.text);
        			text.setText("Proxima cita es: "+fechaDos+". Por favor comunicate al numero: "+celularDos+" .Con el señor(a): "+nombreDos+" para confirmar.");
        			//set up button
        			titulo.setText("Atención");
        			Button button = (Button) layout.findViewById(R.id.buttonOKIS);
        			button.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					builderNotiDos.cancel();

        				}
        			});
        			
        			Button buttonCall = (Button) layout.findViewById(R.id.ButtonLlamar);
        			buttonCall.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					Intent callIntent = new Intent(Intent.ACTION_CALL);
        					callIntent.setData(Uri.parse("tel:"+celularDos));
        					startActivity(callIntent);

        				}
        			});

        			builderNoti = new AlertDialog.Builder(MainActivity.this);
        			builderNoti.setView(layout);
        			builderNotiDos = builderNoti.create();
        			builderNotiDos.show();
        		}
        	});
        }

        
       
    }
    
    @Override
    protected void onPause() {
        super.onPause(); 
        
        prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        if(prefs.getString("notificacion", "").equalsIgnoreCase("ok"))
        {
        	Editor editor = prefs.edit();
    		editor.putString("notificacion","");
    		editor.commit();

			celularDos=prefs.getString("celular","");
    		fechaDos=prefs.getString("fecha","");
    		nombreDos=prefs.getString("nombre","");
    		Log.e("NOMBRE A COLOCAR", nombreDos);
        	runOnUiThread(new Runnable() {
        		public void run() {

        			LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        			View layout = inflater.inflate(R.layout.push,(ViewGroup) findViewById(R.id.layout));

        			TextView titulo=(TextView) layout.findViewById(R.id.title);
        			TextView text=(TextView) layout.findViewById(R.id.text);
        			text.setText("Proxima cita es: "+fechaDos+". Por favor comunicate al numero: "+celularDos+". Con el se�or(a): "+nombreDos+" para confirmar.");
        			//set up button
        			titulo.setText("Atención");
        			Button button = (Button) layout.findViewById(R.id.buttonOKIS);
        			button.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					builderNotiDos.cancel();

        				}
        			});

        			builderNoti = new AlertDialog.Builder(MainActivity.this);
        			builderNoti.setView(layout);
        			builderNotiDos = builderNoti.create();
        			builderNotiDos.show();
        		}
        	});
        }

        
       
    }
    
    @Override
    protected void onStop() {
        super.onStop(); 
        
        prefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
        
        if(prefs.getString("notificacion", "").equalsIgnoreCase("ok"))
        {
        	Editor editor = prefs.edit();
    		editor.putString("notificacion","");
    		editor.commit();

			celularDos=prefs.getString("celular","");
    		fechaDos=prefs.getString("fecha","");
    		nombreDos=prefs.getString("nombre","");
    		Log.e("NOMBRE A COLOCAR", nombreDos);
        	runOnUiThread(new Runnable() {
        		public void run() {

        			LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        			View layout = inflater.inflate(R.layout.push,(ViewGroup) findViewById(R.id.layout));

        			TextView titulo=(TextView) layout.findViewById(R.id.title);
        			TextView text=(TextView) layout.findViewById(R.id.text);
        			text.setText("Proxima cita es: "+fechaDos+". Por favor comunicate al numero: "+celularDos+" . Con el se�or(a): "+nombreDos+" para confirmar.");
        			//set up button
        			titulo.setText("Atención");
        			Button button = (Button) layout.findViewById(R.id.buttonOKIS);
        			button.setOnClickListener(new View.OnClickListener() {
        				@Override
        				public void onClick(View v) {
        					builderNotiDos.cancel();

        				}
        			});

        			builderNoti = new AlertDialog.Builder(MainActivity.this);
        			builderNoti.setView(layout);
        			builderNotiDos = builderNoti.create();
        			builderNotiDos.show();
        		}
        	});
        }

        
       
    }

	public static String md5Java(String message) {
		String digest = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] hash = md.digest(message.getBytes("UTF-8"));
			// converting byte array to Hexadecimal String
			StringBuilder sb = new StringBuilder(2 * hash.length);
			for (byte b : hash) {
				sb.append(String.format("%02x", b & 0xff));
			}
			digest = sb.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return digest;
	}	
	
	//Validar que los campos de loggin y password no esten vacios..
	
	Boolean ValidarCampos(){
		String Usuario=txtLogin.getText().toString();
		String Clave=txtPassword.getText().toString();
		Boolean retval = true;
		
		if(TextUtils.isEmpty(Usuario))
		{
			//txtLogin.setError("Digite un usuario.");
			Toast.makeText(getApplicationContext(), "Digite un usuario", Toast.LENGTH_SHORT).show();
			return retval = false;
		}
		if(TextUtils.isEmpty(Clave))
		{
			//txtPassword.setError("Digite un password");
			Toast.makeText(getApplicationContext(), "Digite un password", Toast.LENGTH_SHORT).show();
			return retval=false;
		}
			
		return retval;
	}

    
}
